<!--功能统计报表-->
<template>
  <div class="m-view-functionReport m-window" v-loading="pageLoading">
    <div class="m-condition">
      <el-row :gutter="10">
        <el-form ref="ruleForm" label-width="70px" :inline-message="true" label-position="left">
          <el-col :span="8">
            <el-form-item label="功能名称" class="rightItem">
              <el-select
                value-key="id"
                v-model="searchForm.codeList"
                placeholder="请选择功能"
                ref="content"
                multiple
                collapse-tags
                @change="valueChange"
              >
                <el-option
                  v-for="(item,index) in funcOptions"
                  :key="index"
                  :label="item.functionName"
                  :value="item.functionCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="期间" class="rightItem">
              <el-date-picker
                v-model="searchForm.startDate"
                placeholder="开始时间"
                value-format="yyyy-MM-dd"
                :clearable="false"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-date-picker
              v-model="searchForm.endDate"
              :clearable="false"
              placeholder="结束时间"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-col>
        </el-form>
        <el-col :span="2" :offset="3">
          <el-button type="primary" @click="searchReport()">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 图表展示 -->
    <div class="m-top3">
      <div class="m-chartTitle">功能使用统计</div>
      <ve-histogram
        :data="chartData"
        :settings="chartSetting"
        :mark-line="markLine"
        :mark-point="markPoint"
        :toolbox="toolbox"
        :extend="extend"
        :events="chartEvents"
        :grid="grid"
        :data-empty="chartData.rows.length==0"
        height="450px"
        v-loading="loading"
      ></ve-histogram>
    </div>
    <!-- 查看功能使用明细弹窗 -->
    <el-dialog
      title="功能使用明细"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :inline-message="true"
    >
      <div class="dialog-body">
        <el-button type="primary" @click="searchDetailData('exportDetail',2)">导出</el-button>
        <agGridComponents
          ref="agGridComponent"
          :getGridOptions="gridOptions"
          :getColumnDefs="columnDefs"
          :isColFit="true"
        ></agGridComponents>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @prev-click="handlePrevClick"
          @next-click="handleNextClick"
          :current-page="pageInfo.current"
          :page-sizes="[30,50,100,150,200]"
          :page-size="pageInfo.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import agGridComponents from "@/components/agGridComponents"
import serviceTime from "@/public/serverTime"
import { exportExcel } from 'lesso-common/public/utils'
import Msg from "@/public/message"
import _Api from "@/api"
export default {
  data () {
    this.grid = {
      show: false,
      top: 50,
      left: 10,
      right: 50,
      bottom: '0%',
      containLabel: true
    }
    return {
      dialogVisible: false,
      loading: false,
      pageLoading: false,
      // 图表数据为空   
      dataEmpty: false,
      // 查询项   
      searchForm: {
        codeList: [],
        startDate: '',
        endDate: ''
      },
      // 功能列表   
      funcOptions: [
      ],
      // 分页相关  
      pageInfo: {
        size: 30,
        current: 1,
        total: 0
      },
      // 图表数据   
      chartData: {
        columns: ['functionName', 'totalSum'],
        rows: []
      },
      // 图表配置   
      chartSetting: {
        metrics: ['totalSum'],
        labelMap: {
          'totalSum': '使用次数'
        },
        dimension: ['functionName']
      },
      // 配置图表标线
      markLine: {
        label: {
          show: true,
          position: 'end',
          color: 'red',
          formatter: (params) => {
            if (params.value) {
              return params.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
            } else {
              return 0
            }
          }
        },
        data: [
          { type: 'average', name: '平均值' }
        ]
      },
      // 配置图标标点   
      markPoint: {
        label: {
          show: true,
          position: 'inside',
          formatter: (params) => {
            if (params.value) {
              return params.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
            } else {
              return 0
            }
          }
        },
        data: [
          { type: 'max', name: '最大值' },
          { type: 'min', name: '最小值' }
        ]
      },
      // 设置图表工具栏   
      toolbox: {
        feature: {
          magicType: { type: ['line', 'bar'] },
          saveAsImage: {}
        },
        right: 20
      },
      extend: {
        series (v) {
          v.forEach(i => {
            i.barMaxWidth = 40
            i.barMinHeight = 2
          })
          return v
        },
        'xAxis.0.axisLabel.rotate': 45
      },
      // 图表事件  
      chartEvents: {
        click: this.chartEvent
      },
      gridOptions: {},
      // 当前选择的功能
      selectedCode: ''
    }
  },
  props: {
  },
  beforeMount () {
    this.columnDefs = [
      { headerName: "功能名称", field: "functionName", width: 140 },
      { headerName: "使用时间", field: "createDate", width: 160 },
      { headerName: "使用人", field: "creator", width: 100 },
      { headerName: "所属供应商", field: "supplierName", width: 160, tooltipField: 'supplierName' },
      { headerName: "供应商联系方式", field: "phone", width: 160 },
      { headerName: "签章人", field: "linkMan", width: 160 },
      { headerName: "签章人手机", field: "linkNumber", width: 160 },
      { headerName: "签章人邮箱", field: "mail", width: 160 },
    ]
  },
  mounted () {
    // 初始化数据
    this.initDate()
    // 获取功能下拉数据
    this.loadFunctionOptions()
  },
  methods: {
    // 选择值改变
    valueChange (val) {
      //   this.searchReport()
    },
    // 点击图表事件
    chartEvent (e) {
      if (e.componentType == 'series') {
        this.pageInfo.size = 30
        this.pageInfo.current = 1
        let chartItem = this.chartData.rows[e.dataIndex]
        this.selectedCode = chartItem.functionCode
        this.searchDetailData('detail', 1)
        this.dialogVisible = true
      }
    },
    // 查询明细数据
    searchDetailData (type, flag) {
      /**
      *  @property {number} flag 1打开明细弹窗;2导出明细数据;3不传正常查询
      *  @property {string} type 'detail'分页查询明细;'exportDetail'查询全部明细
      */
      const { size, current } = this.pageInfo
      let obj = {}
      if (flag == 2) {
        obj = {
          queryType: type,
          codeList: [this.selectedCode],
        }
      } else {
        obj = {
          queryType: type,
          codeList: [this.selectedCode],
          currentPage: current,
          pageSize: size
        }
      }
      this.getReportData(obj).then(data => {
        if (flag == 1) {
          this.$refs.agGridComponent.gridOptions.api.setRowData(data.rows)
          this.pageInfo.total = data.total
          this.dialogVisible = true
        } else if (flag == 2) {
          this.exportDetailsData(data.rows)
          return
        }
        this.$refs.agGridComponent.gridOptions.api.setRowData(data.rows)
        this.pageInfo.total = data.total
      }).catch(err => {
        Msg.showErrorMsg(err)
      })
    },
    // 弹窗关闭前回调
    handleClose () {
      this.dialogVisible = false
      this.selectedCode = ''
    },
    // 每页显示条数改变回调
    handleSizeChange (val) {
      this.pageInfo.size = val
      this.searchDetailData('detail')
    },
    // 页码改变回调
    handleCurrentChange (val) {
      this.pageInfo.current = val
      this.searchDetailData('detail')
    },
    // 点击上一页回调
    handlePrevClick (val) {
      this.pageInfo.current = val
    },
    // 点击下一页回调
    handleNextClick (val) {
      this.pageInfo.current = val
    },
    // 初始化查询时间
    initDate () {
      // 日期范围默认近6个月内
      serviceTime.getServiceTime().then((serviceTime) => {
        let startDate = new Date(serviceTime.getTime() - 3600 * 1000 * 24 * 30 * 6).Format('yyyy-MM-dd')
        let endDate = serviceTime.Format("yyyy-MM-dd")
        this.searchForm.startDate = startDate
        this.searchForm.endDate = endDate
        // this.searchReport()
      }).catch(err => {
        Msg.showErrorMsg(err)
      })
    },
    // 获取功能下拉内容
    loadFunctionOptions () {
      this.pageLoading = true
      _Api.getFunctionOptions().then(({ data }) => {
        this.pageLoading = false
        if (data.code == 1) {
          this.funcOptions = data.rows
        } else {
          Msg.showErrorMsg(data.info)
        }
      }).catch(err => {
        this.pageLoading = false
        Msg.showErrorMsg(err.data.message)
      })
    },
    // 查询图表汇总数据
    searchReport () {
      const { codeList } = this.searchForm
      let obj = {
        queryType: 'summary',
        codeList,
      }
      this.dataEmpty = false
      this.getReportData(obj).then(data => {
        this.chartData.rows = data.rows
      }).catch(err => {
        Msg.showErrorMsg(err)
      })
    },
    // 导出明细数据
    exportDetailsData (rowData) {
      let excelData = []
      rowData.forEach(row => {
        excelData.push({
          '功能名称': row.functionName,
          '使用时间': row.createDate,
          '使用人': row.creator,
          '所属供应商': row.supplierName,
          '供应商联系方式': row.phone,
          "签章人":row.linkMan,
          "签章人手机":row.linkNumber,
          "签章人邮箱":row.mail,
        })
      })
      let params = {
        data: excelData,
        fileName: '功能使用明细.xlsx'
      }
      exportExcel(params)
    },
    // 获取数据
    getReportData (obj) {
      const { startDate, endDate } = this.searchForm
      let params = {
        ...obj,
        dateStart: startDate,
        dateEnd: endDate
      }
      return new Promise((resolve, reject) => {
        this.loading = true
        _Api.getFunctionReport(params).then(({ data }) => {
          this.loading = false
          if (data.code == 1) {
            resolve(data)
          } else {
            reject(data.info)
          }
        }).catch(err => {
          this.loading = false
          reject(err.data.message)
        })
      })
    }
  },
  components: {
    agGridComponents
  }
}
</script>

<style lang="less" scoped>
.m-view-functionReport {
  overflow-y: auto;
  overflow-x: hidden;
  .dialog-body {
    height: 400px;
    /deep/ .el-button {
      margin-bottom: 10px;
    }
    .m-agTableContent {
      height: 92%;
    }
  }
  .m-top3 {
    .m-chartTitle {
      position: absolute;
      left: 10px;
      font-size: 14px;
    }
    /deep/ .v-charts-data-empty {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  }
}
</style>